package com.kx.hackathon.controller;

import com.kx.hackathon.enums.CommandEnum;
import com.kx.hackathon.service.HandlerService;
import com.kx.hackathon.service.impl.BaikeServiceImpl;
import com.kx.hackathon.util.SpringContextUtil;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class HandlerController {
    @Autowired
    @Qualifier("BaikeServiceImpl")
    private BaikeServiceImpl baikeService;

    @PostMapping("/handle")
    public String handle(@RequestBody String msg, HttpServletRequest request) {
        msg = msg.trim();
        HttpSession session = request.getSession();
        String doing = (String) session.getAttribute("doing");
        String commmandName = doing;
        int spaceIndex = msg.indexOf(' ');
        String command = msg;
        String arg = null;
        if (spaceIndex >= 0) {
            command = msg.substring(0, spaceIndex);
            arg = msg.substring(spaceIndex + 1).trim();
        }
        if (doing == null) {
            CommandEnum commandEnum = CommandEnum.getByCommand(command);
            if (commandEnum == null) {
                commandEnum = CommandEnum.Default;
            }
            commmandName = commandEnum.name();
        } else {
            if ("exit".equals(msg)) {
                session.removeAttribute("doing");
            }
        }
        try {
            HandlerService handler = (HandlerService) SpringContextUtil.getBean(commmandName + "ServiceImpl");
            try {
                if (doing == null) {
                    if (handler.needInit()) {
                        session.setAttribute("doing", command);
                        return handler.init(msg, arg);
                    } else {

                        return handler.handle(msg, arg);
                    }
                } else {
                    return handler.handle(msg, arg);
                }
            } catch (Exception e) {
                return baikeService.handle(msg ,arg);
            }
        } catch (NoSuchBeanDefinitionException e) {
            return "没有找到" + commmandName + "的处理器";
        }
    }
}
